<!--
 * @Description: 
 * @Author: mxy
 * @Date: 2022-11-12 20:58:39
 * @LastEditors: mxy
 * @LastEditTime: 2022-11-12 21:14:59
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function ajax({ method, url, params, data }) {
            //第一步  实例化
            const xhr = new XMLHttpRequest()

            //第二步  添加事件且判断状态码
            xhr.addEventListener('load', function () {
                if (xhr.status >= 200 && xhr.status < 300) {
                    console.log('请求成功', JSON.parse(xhr.response));
                } else if (xhr.status >= 300) {
                    console.log('请求失败', JSON.parse(xhr.response));
                }
            })

            //第三步  遍历params对象转为字符串拼接到url后边
            let arr = []
            for (let k in params) {
                arr.push(`${k}=${params[k]}`)
            }
            xhr.open(method, `${url}?${arr.join('&')}`)

            //第四步  判断data是什么类型请求头，设置相应的请求体
            if (data instanceof FormData) {
                xhr.send(data)
            } else if (data instanceof Object) {
                xhr.setRequestHeader('Content-Type', 'application/json')
                xhr.send(JSON.stringify(data))
            } else if (typeof data === 'string') {
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
                xhr.send(data)
            } else {
                //以上情况都不是说明没有data，直接send
                xhr.send()
            }


        }

        ajax({
            method: 'GET',
            url: 'http://www.itcbc.com:3006/api/getbooks',
            params: {
                appkey: 'xiaomeng'
            }
        })


        // ---------------------------
        ajax({
            method: 'POST',
            url: 'http://www.itcbc.com:3006/api/addbook',
            data: {
                bookname: 'aa',
                author: 'bb',
                publisher: 'cc',
                appkey: 'xiaomeng'
            }
        })
    </script>
</body>

</html>